'''
Created on 2024年8月18日

@author: Administrator
'''

import sys,argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from pandas.tests.scalar.interval.test_interval import interval

def randomGrid(N):
    return np.random.choice([255,0],N*N,p=[0.2,0.8]).reshape(N,N)


def addGlider(i,j,grid):
    glider = np.array([[0,0,255],[255,0,255],[0,255,255]])
    grid[i:i+3,j:j+3] = glider

def update(frameNum,img,grid,N):
    newGrid = grid.copy()
    for i in range(N):
        for j in range(N):
            
            total = ((grid[i,(j-1)%N]+grid[i,(j+1)%N]+
                     grid[(i-1)%N,j]+grid[(i+1)%N,j]+
                     grid[(i-1)%N,(j-1)%N]+grid[(i-1)%N,(j+1)%N]+
                     grid[(i+1)%N,(j-1)%N]+grid[(i+1)%N,(j+1)%N]
                     )/255)
            if grid[i,j] == 255:
                if (total < 1) or (total > 3):
                    newGrid[i,j] = 0
            else:
                if total == 3:
                    newGrid[i,j] = 255
    img.set_data(newGrid) 
    grid[:] = newGrid[:]
    return img,

def main():
    parser = argparse.ArgumentParser(description="Runs Conway's Game of Life simulation.")
    
    parser.add_argument('--grid-size',dest='N',required=False)     
    parser.add_argument('--interval',dest='interval',required=False)     
    parser.add_argument('--glider',action='store_true',required=False)     
    parser.add_argument('--gosper',action='store_true',required=False)
    args = parser.parse_args()
    
    N = 100
    
    updateInterval = 50
    if args.interval:
        updateInterval = int(args.interval)
    
    
    grid = np.array([])
    if args.glider:
        grid = np.zeros(N*N).reshape(N,N)
        addGlider(1, 1, grid)
    elif args.gosper:
        grid = np.zeros(N*N).reshape(N,N)
        addGosperGliderGun(10,10,grid)
    else:
        if args.N and int(args.N)>8:
            N = int(args.N)
        
        grid = randomGrid(N)
    
    fig,ax = plt.subplots()
    img = ax.imshow(grid,interpolation='nearest')
    ani = animation.FuncAnimation(fig,update,fargs=(img,grid,N,),
                                  frames = 10,
                                  interval = updateInterval
                                  )          
    plt.show()


if __name__ == '__main__':
    main()
        


